package com.yufubao.service.service.applet.product.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yufubao.framework.enums.CommonExceptionEnum;
import com.yufubao.framework.exception.BaseException;
import com.yufubao.framework.result.PageUtils;
import com.yufubao.framework.result.ResponseResult;
import com.yufubao.framework.util.CopyBean;
import com.yufubao.framework.util.MyCollUtil;
import com.yufubao.framework.util.page.Query;
import com.yufubao.model.pojo.applet.product.SupplierProductCategoryEntity;
import com.yufubao.model.vo.applet.product.SupplierProductCategoryVo;
import com.yufubao.service.mapper.applet.product.SupplierProductCategoryDao;
import com.yufubao.service.service.applet.product.SupplierProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("supplierProductCategoryService")
public class SupplierProductCategoryServiceImpl extends ServiceImpl<SupplierProductCategoryDao, SupplierProductCategoryEntity> implements SupplierProductCategoryService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SupplierProductCategoryEntity> page = this.page(
                new Query<SupplierProductCategoryEntity>().getPage(params),
                new QueryWrapper<SupplierProductCategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @return com.yufubao.common.result.ResponseResult
     * @description applet产品分类树化
     * @author zhangyiheng
     * @date 2024/8/26 21:39
     */
    @Override
    public ResponseResult listTree() {

        try {
//            //查询缓存
//            List<SupplierProductCategoryVo> cacheList = (List<SupplierProductCategoryVo>) redisTemplate.opsForValue().get(SUPPLIER_PRODUCT_CATEGORY);
//            if (!Objects.isNull(cacheList)) {
//                return MyCollUtil.isNotEmpty(cacheList) ? new ResponseResult().ok(cacheList) : ResponseResult.errorResult(CommonExceptionEnum.DATE_NOT_DATA);
//            }

            List<SupplierProductCategoryEntity> list = this.list();
            if (!MyCollUtil.isNotEmpty(list)) {
                throw new BaseException("无商品分类信息");
            }


            //树化并排序
            List<SupplierProductCategoryVo> categoryVos = getCategoryTreeVos(list);

//            redisTemplate.opsForValue().set(SUPPLIER_PRODUCT_CATEGORY, categoryVos);


            return MyCollUtil.isNotEmpty(categoryVos) ? new ResponseResult().ok(categoryVos) : ResponseResult.errorResult(CommonExceptionEnum.DATE_NOT_DATA);
        } catch (BaseException e) {
            throw new BaseException(e.getErrorCode(), e.getMessage());
        }
    }


    private List<SupplierProductCategoryVo> getCategoryTreeVos(List<SupplierProductCategoryEntity> list) {
        List<SupplierProductCategoryVo> vos = CopyBean.copyBeanList(list, SupplierProductCategoryVo.class);

        Map<Long, SupplierProductCategoryVo> map = new HashMap<>();

        for (SupplierProductCategoryVo categorys : vos) {
            map.put(categorys.getCategoryId(), categorys);
        }

        List<SupplierProductCategoryVo> categoryVos = new ArrayList<>();

        for (SupplierProductCategoryVo value : map.values()) {
            SupplierProductCategoryVo fatherCategory = map.get(value.getParentId());

            if (!Objects.isNull(fatherCategory)) {
                //说明有父分类
                if (CollUtil.isEmpty(fatherCategory.getChildren())) {
                    fatherCategory.setChildren(new ArrayList<>());
                }
                fatherCategory.getChildren().add(value);
                //排序
                categorySonSort(fatherCategory.getChildren());
            } else {
                categoryVos.add(value);
                categorySonSort(categoryVos);
            }
        }
        return categoryVos;
    }


    private void categorySonSort(List<SupplierProductCategoryVo> sonSort) {

        sonSort.sort(new Comparator<SupplierProductCategoryVo>() {
            @Override
            public int compare(SupplierProductCategoryVo o1, SupplierProductCategoryVo o2) {
                return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort());
            }
        });
    }



    /**
     * @param catelogId
     * @return java.lang.Long[]
     * @description 回显分类所有层级路径id
     * @author zhangyiheng
     * @date 2024/8/28 22:38
     */
    @Override
    public Long[] getCatelogIdPath(Long catelogId) {
        List<Long> catelogIdPath = new ArrayList<>();
        getCatIdPath(catelogIdPath, catelogId);

        //反转元素值
        Collections.reverse(catelogIdPath);

        return catelogIdPath.toArray(new Long[catelogIdPath.size()]);
    }



    private void getCatIdPath(List<Long> catelogIdPath, Long catelogId) {
        SupplierProductCategoryEntity category = this.getById(catelogId);
        //为空代表顶级
        if (!Objects.isNull(category)) {
            catelogIdPath.add(category.getCategoryId());
            getCatIdPath(catelogIdPath, category.getParentId());
        }
    }

    /**
     * @param category
     * @return void
     * @description 修改
     * @author zhangyiheng
     * @date 2024/9/18 18:48
     */
    @Override
    @Transactional
    public void updateByIdAndintermediateTable(SupplierProductCategoryEntity category) {
        this.updateById(category);
    }

    /**
     * @param list
     * @return void
     * @description 删除
     * @author zhangyiheng
     * @date 2024/9/18 18:59
     */
    @Override
    @Transactional
    public void removeMenuByIds(List<Long> list) {
        this.removeByIds(list);
    }
}